<template>
  <!-- 轮播图编辑和新增 -->
  <div class="carousel-edit">
    <div class="carousel-edit-content">
      <el-form
        ref="carouselEditForm"
        :model="carouselEditForm"
        label-width="100px"
        class="edit-form"
      >
        <!-- 业务名称 -->
        <el-form-item label="业务名称" prop="name">
          <el-input
            v-model="carouselEditForm.name"
            placeholder="请输入"
            style="width: 300px"
          ></el-input>
        </el-form-item>

        <!-- 类型 -->
        <el-form-item label="类型" prop="type">
          <el-input
            v-model="carouselEditForm.type"
            placeholder="banner"
            style="width: 300px"
          ></el-input>
        </el-form-item>

        <!-- 封面图片 -->
        <el-form-item label="封面图片" prop="imageUrl">
          <div class="upload-image-container">
            <el-upload
              class="avatar-uploader"
              :action="action"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <div
                v-if="carouselEditForm.imageUrl"
                class="avatar-uploader-preview"
              >
                <img :src="carouselEditForm.imageUrl" class="avatar" />
              </div>
              <div v-else class="upload-image-btn-container">
                <div class="upload-image-btn">
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <span>上传图片</span>
                </div>
                <p class="upload-image-tip">
                  <el-tooltip
                    style="padding-left: 10px"
                    effect="dark"
                    content="Top Left 提示文字"
                    placement="top-start"
                  >
                    <i class="el-icon-warning f15" style="color: #8c8c8c"></i>
                  </el-tooltip>
                  格式支持jpg、png，单张图片大小不超过10MB
                </p>
              </div>
            </el-upload>
            <!-- <div class="upload-image-btn" @click="handleImageUpload">
              <i class="el-icon-plus"></i>
              <span>上传图片</span>
            </div> -->
            <!-- <p class="upload-image-tip">
              格式支持jpg、png，单张图片大小不超过10MB
            </p> -->
          </div>
        </el-form-item>

        <!-- 发布选项 -->
        <el-form-item label="发布选项" prop="publishOption">
          <el-radio-group v-model="carouselEditForm.publishOption">
            <el-radio label="textImage">图文展示</el-radio>
            <el-radio label="linkJump">链接跳转</el-radio>
            <el-radio label="noAction">无操作</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 链接输入框（仅在选择"链接跳转"时显示） -->
        <el-form-item
          v-if="carouselEditForm.publishOption === 'linkJump'"
          label="跳转链接"
          prop="link"
        >
          <el-input
            v-model="carouselEditForm.link"
            placeholder="请输入链接地址"
            style="width: 300px"
          ></el-input>
        </el-form-item>

        <!-- 富文本编辑器（仅在选择"图文展示"时显示） -->
        <el-form-item v-if="carouselEditForm.publishOption === 'textImage'">
          <div class="editor-container">
            <quill-editor
              v-model="content"
              :options="editorOptions"
              @blur="onEditorBlur"
              @focus="onEditorFocus"
              @change="onEditorChange"
            />
          </div>
        </el-form-item>

        <!-- 发布按钮 -->
        <div class="publish-btn-container">
          <CustomButton
            text="发布"
            size="medium"
            type="primary"
            :customStyle="{
              padding: '10px 25px',
            }"
            @click="handleClick()"
          />
          <!-- <el-button type="primary" @click="handleSubmit" class="publish-btn"
            >发布</el-button
          > -->
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { upload } from "@/api/upload.js";

export default {
  name: "CarouselIndexEdit",
  props: {
    datas: Object,
  },
  data() {
    return {
      // 上传接口地址（替换为实际接口）
      action: upload,
      // 请求头（携带token）
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token"),
      },
      // 单图文件列表（用于回显）
      singleFileList: [],
      // 富文本编辑器的内容
      content: "",
      // 编辑器的配置项
      editorOptions: {
        // 配置工具栏的按钮
        toolbar: [
          ["bold", "italic", "underline", "strike"], // 加粗、斜体、下划线、删除线
          ["blockquote", "code-block"], // 引用、代码块
          [{ header: 1 }, { header: 2 }], // 1、2 级标题
          [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
          [{ indent: "-1" }, { indent: "+1" }], // 缩进
          ["link", "image", "video"], // 链接、图片、视频
          ["clean"], // 清除格式
        ],
      },
      carouselEditForm: {
        name: "",
        type: "banner",
          imageUrl: "",
        image: "",
        content: "",
        publishOption: "textImage", // 默认选择链接跳转
        sort: 0,
        link: "", // 新增：用于存放跳转链接
      },
    };
  },
  // 组件挂载时执行
  mounted() {
    console.log("datas", this.datas);
    if (this.datas) {
      this.carouselEditForm = this.datas;
    }
    // 初始设置编辑器高度
    this.setEditorHeight();
    // 添加窗口大小变化事件监听
    window.addEventListener("resize", this.handleResize);
  },
  // 组件卸载时执行
  beforeUnmount() {
    // 移除事件监听，避免内存泄漏
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    // 上传头像
    handleAvatarSuccess(res) {
      console.log("是否上传成功", res);
      this.carouselEditForm.imageUrl = res.data.url;
      //   this.setAVATR(res.data.url)
      this.$message({
        message: "上传成功，请保存修改！",
        type: "success",
      });
    },
    // 单图上传成功
    handleSingleSuccess(response, file, fileList) {
      console.log("单图上传成功", response, file, fileList);
      // 可在这里获取图片URL，用于表单提交
      // const imageUrl = file.url;
    },
    // 编辑器失去焦点时触发
    onEditorBlur() {
      console.log("富文本编辑器失去焦点");
    },
    // 编辑器获得焦点时触发
    onEditorFocus() {
      console.log("富文本编辑器获得焦点");
    },
    // 编辑器内容变化时触发
    onEditorChange() {
      console.log("富文本编辑器内容发生变化");
    },
    // 提交富文本内容的方法
    submitContent() {
      // 这里可以添加将内容发送到后端等逻辑
    },
    handleSubmit() {
      console.log("提交的富文本内容：", this.content, this.carouselEditForm);
      this.$refs.carouselEditForm.validate((valid) => {
        if (valid) {
          // 提交表单数据前，将富文本内容同步到表单对象中
          if (this.carouselEditForm.publishOption === "textImage") {
            this.carouselEditForm.content = this.content;
          } else {
            // 非图文展示模式下清空内容
            this.carouselEditForm.content = "";
          }

          this.$emit("submit", this.carouselEditForm);
        } else {
          console.log("表单验证失败");
        }
      });
    },

    handleImageUpload() {
      // 这里可以实现图片上传逻辑
      console.log("点击了上传图片");
      // 通常会打开文件选择对话框或调用上传组件
    },
    // 核心方法：动态计算并设置编辑器高度
    setEditorHeight() {
      // 获取窗口高度
      const windowHeight = window.innerHeight;

      // 获取其他元素占用的总高度（例如：标题、表单其他字段、按钮等）
      // 这里可以根据实际页面结构进行调整
      const otherElementsHeight = 600; // 估算值，根据实际情况调整
      const editorContainer = document.querySelector(".ql-container");
      console.log("获取元素高度:", windowHeight, editorContainer);

      // 计算编辑器应该占用的高度
      const editorHeight = Math.max(
        windowHeight - otherElementsHeight,
        230 // 确保最小高度
      );

      // 获取编辑器元素并设置高度
      //   const editorContainer = document.querySelector('.editor-container >>> .ql-container');
      if (editorContainer) {
        editorContainer.style.height = `${editorHeight}px`;
      }
    },

    // 处理窗口大小变化事件
    handleResize() {
      this.setEditorHeight();
    },
  },
};
</script>

<style scoped>
.carousel-edit {
  width: 100%;
  height: calc(100vh - 50px);
  background-color: #fff;
  position: relative;
}

.carousel-edit-header {
  width: 100%;
  height: 50px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-bottom: 1px solid #e8e8e8;
}

.carousel-edit-header-left {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-left: 20px;
}

.carousel-edit-header-left-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.carousel-edit-content {
  padding: 20px;
  height: 100%;
}

.edit-form {
  width: 100%;
}

.upload-image-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.avatar-uploader-preview {
  border: 1px solid red;
  height: 100px;
}
.upload-image-btn-container {
  display: flex;
  align-items: flex-end;
}
/* 上传图片按钮样式 */
.upload-image-btn {
  width: 120px;
  height: 80px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-image-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

.upload-image-btn i {
  font-size: 24px;
  margin-bottom: 5px;
}

.upload-image-tip {
  font-size: 12px;
  color: #909399;
  margin: 0;
}

.carousel-edit-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.edit-form {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 关键修改：使用视口高度减去其他元素占用的空间 */
.editor-container {
  flex: 1;
  min-height: 0; /* 允许flex子元素收缩到内容以下 */
}

/* 确保quill-editor内部的编辑区域也有足够的高度 */
.editor-container >>> .ql-container {
  height: calc(
    100vh - 900px
  ); /* 基于视口高度动态计算，减去其他元素占用的高度 */
  min-height: 230px; /* 设置最小高度，防止在小屏幕上过高 */
}

.editor-container >>> .ql-editor {
  min-height: 100%;
}

/* 响应式调整，确保在不同屏幕尺寸下正常显示 */
@media (max-height: 768px) {
  .editor-container >>> .ql-container {
    height: calc(100vh - 750px);
  }
}

@media (max-height: 600px) {
  .editor-container >>> .ql-container {
    height: calc(100vh - 300px);
  }
}
.editor-toolbar {
  height: 40px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  padding: 0 10px;
  gap: 8px;
}

.toolbar-btn {
  width: 28px;
  height: 28px;
  border: none;
  background: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 3px;
  transition: background-color 0.3s;
}

.toolbar-btn:hover {
  background-color: #e4e7ed;
}

.toolbar-separator {
  width: 1px;
  height: 16px;
  background-color: #dcdfe6;
  margin: 0 5px;
}

.editor-content {
  padding: 10px;
}
/* 发布按钮样式调整，确保固定在底部 */
.publish-btn-container {
  position: absolute;
  bottom: 5px;
  right: 20px;
}

.publish-btn:hover {
  background-color: #66b1ff;
}
</style>
